﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DBQueryTools
{
    /// <summary>
    /// socket 链接管理类 
    /// </summary>
    internal static class SocketPool
    {
        private static object GetLock = new object();

        //key 为ip 的异步管理容器
        private static Dictionary<string, AsyncClient> AsyncMap = new Dictionary<string, AsyncClient>();
        //定时器
        private static System.Timers.Timer _HeartbeatTimer;

        public static void Init()
        {
            _HeartbeatTimer = new System.Timers.Timer();
            _HeartbeatTimer.Interval = 20000;
            _HeartbeatTimer.Elapsed += new System.Timers.ElapsedEventHandler(_Heartbeat);
            //设置是执行一次（false）还是一直执行(true)；  
            _HeartbeatTimer.AutoReset = true;
            _HeartbeatTimer.Start();
        }

        //遍历所有AsyncClient 判断是否有效
        private static void _Heartbeat(object sender, System.Timers.ElapsedEventArgs e)
        {
            lock (GetLock)
            {
                foreach (KeyValuePair<string, AsyncClient> kvp in AsyncMap)
                {
                    AsyncClient client = kvp.Value;
                    if (!client.IsConnect()) //10秒内没有消息交互 可以认为已断开链接
                    {
                        AsyncMap.Remove(kvp.Key);
                    }
                }  
            }
        }

        //获取一个AsyncClient
        public static AsyncClient CreateAsyncClient(string key, string loginIP, string loginName, DealMsgDelegate _deal, object token)
        {
            if (AsyncMap.ContainsKey(key))
            {
                return AsyncMap[key];
            }
            else
            {
                AsyncClient client = new AsyncClient(loginIP, loginName, _deal, token);
                AsyncMap.Add(key, client);
            }
            return AsyncMap[key];
        }
        
        //获取一个AsyncClient 不存在则返回空
        public static AsyncClient GetAsyncClientByKey(string key)
        {
            if (!AsyncMap.ContainsKey(key))
            {
                return null;
            }
            return AsyncMap[key];;
        }

        //手动删除链接
        public static void RemoveAsyncClient(string key)
        {
            lock (GetLock)
            {
                if (AsyncMap.ContainsKey(key))
                {
                    AsyncMap.Remove(key);
                }
            }
        }

    }
}
